package com.kfm.servlet;

import com.kfm.model.FileDO;
import com.kfm.service.UploadService;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/upload")
@MultipartConfig(maxFileSize = 1024 * 1024 * 10, location = "D:\\temp") // 支持上传文件了
public class UploadServlet extends HttpServlet {

    public static Map<String, FileDO> map = new HashMap<>();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        Part part = req.getPart("f");
        String username = req.getParameter("username");

        String name = part.getName();

        String submittedFileName = part.getSubmittedFileName();

        String contentType = part.getContentType();

        long size = part.getSize();

//        System.out.println(req.getServletContext().getMimeType(part.getSubmittedFileName()));

//        part.getInputStream()

//        int i = submittedFileName.lastIndexOf(".");
//
//        String sub = submittedFileName.substring(i);

        // 业务层
        UploadService service = new UploadService();
        // 保存文件
        String path = service.save(part);

        FileDO fileDO = new FileDO();
        fileDO.setName(submittedFileName);
        fileDO.setPath(path);
        fileDO.setSize(size);

        map.put(username, fileDO);

        resp.setContentType("text/plain;charset=utf-8");
        resp.getWriter().write("上传成功");
    }
}
